package a3_stack;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

/**
 * 基于数组的顺序栈实现
 */
public class MyStack<E> {

    private int size;

    private List<E> list = new ArrayList<>();

    //将val入栈
    public void push(E val) {
        list.add(val);
        size ++;
    }

    //弹出栈顶元素，并返回值
    public E pop() {
        if(isEmpty()){
            throw new NoSuchElementException("stack is empty! cannot pop!");
        }
        E val = list.remove(size - 1);
        size --;
        return val;
    }

    //返回栈顶元素
    public E peek() {
        if(isEmpty()){
            throw new NoSuchElementException("stack is empty! cannot peek!");
        }
        return list.get(size - 1);
    }

    //判断栈是否为空
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for(int i = 0; i < size; i++) {
            sb.append(list.get(i));
            if(i != size - 1){
                sb.append(", ");
            }
        }
        sb.append("] top");
        return sb.toString();
    }
}
